﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace ShareMarking.Systems.Services
{
	/// <summary>
	/// 
	/// </summary>
	public class ObjectMapper {
		/// <summary>
		/// 
		/// </summary>
		/// <param name="sourceType"></param>
		/// <param name="targetType"></param>
		/// <returns></returns>
		public static IList<PropertyMapper> GetMapperProperties(Type sourceType, Type targetType) {
			var sourceProperties = sourceType.GetProperties();
			var targetProperties = targetType.GetProperties();

			return (from s in sourceProperties
					from t in targetProperties
					where s.Name == t.Name && s.CanRead && t.CanWrite && s.PropertyType == t.PropertyType
					select new PropertyMapper {
						SourceProperty = s,
						TargetProperty = t
					}).ToList();
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="source"></param>
		/// <param name="target"></param>
		public static void CopyProperties(object source, object target) {
			var sourceType = source.GetType();
			var targetType = target.GetType();
			var mapperProperties = GetMapperProperties(sourceType, targetType);

			for (int index = 0, count = mapperProperties.Count; index < count; index++) {
				var property = mapperProperties[index];
				var sourceValue = property.SourceProperty.GetValue(source, null);
				property.TargetProperty.SetValue(target, sourceValue, null);
			}
		}
	}

	/// <summary>
	/// 
	/// </summary>
	public class PropertyMapper {
		/// <summary>
		/// 
		/// </summary>
		public PropertyInfo SourceProperty {
			get;
			set;
		}

		/// <summary>
		/// 
		/// </summary>
		public PropertyInfo TargetProperty {
			get;
			set;
		}
	}
}
